package tech.edwardvan.springsecuritydemo.security.handler;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import tech.edwardvan.springsecuritydemo.common.ResponseCode;
import tech.edwardvan.springsecuritydemo.common.ServerResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT权限不足处理程序
 * 认证成功的用户访问受保护的资源时权限不够
 *
 * @author EdwardVan
 */
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServerResponse serverResponse = new ServerResponse(ResponseCode.FORBIDDEN.getCode(), ResponseCode.FORBIDDEN.getDesc(), exception != null ? exception.getMessage() : null);
        IoUtil.writeUtf8(response.getOutputStream(), true, JSONUtil.toJsonStr(serverResponse));
    }
}
